import compute from '../lib/compute'
import { trimSpace, digitalize } from '../utils/tools'

import ResultComponent from '../components/Result'
import InputGroupComponent from '../components/InputGroup'
import BtnGroupComponent from '../components/BtnGroup'

//  利用装饰器进行扩展
@compute
export default class Calculator {
  constructor (el) {
    // 模块名字
  	this.name = 'Calculator'
  	this.el = el

    this.resultComponent = new ResultComponent()
    this.inputGroupComponent = new InputGroupComponent()
    this.btnGroupComponent = new BtnGroupComponent()
  }

  init () {
  	this.render()
    this.bindEvent()
  }

  render () {
    // 三个组件，就需要三次appendChild,会因此三次重绘重排
    // 可以声明文档碎片
    const oFrag = document.createDocumentFragment()
    oFrag.appendChild(this.resultComponent.tpl())
    oFrag.appendChild(this.inputGroupComponent.tpl())
    oFrag.appendChild(this.btnGroupComponent.tpl())

    this.el.appendChild(oFrag)
  }

  bindEvent () {
    const el = this.el

    this.oResult = el.getElementsByClassName('result')[0]
    this.oBtnGroup = el.getElementsByClassName('btn-group')[0]
    this.oInputs = el.getElementsByClassName('num-input')

  	this.oBtnGroup.addEventListener('click', this.onBtnClick.bind(this), false)
  }

  onBtnClick (ev) {
  	const e = ev || window.event,
      tar = e.target || e.srcElement,
      tagName = tar.tagName.toLowerCase()

  	if (tagName === 'button') {
      const method = tar.getAttribute('data-method'),
        fVal = digitalize(trimSpace(this.oInputs[0].value)),
        sVal = digitalize(trimSpace(this.oInputs[1].value))
      
      this.setResult(method, fVal, sVal)
  	}
  }

  setResult (method, fVal, sVal) {
    this.oResult.innerText = this[method](fVal, sVal)
  }
}









